package com.heima.behavior.interceptor;

import com.aliyuncs.utils.StringUtils;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Component
public class BehaviorInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if(StringUtils.isEmpty(userId)){
            return false;
        }
        UserThreadLocalUtils.setUserId(Integer.parseInt(userId));
        log.info("拦截器的线程名:{},id:{}",Thread.currentThread(),UserThreadLocalUtils.getUserId());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("删除线程id:{}",UserThreadLocalUtils.getUserId());
        UserThreadLocalUtils.removeUser();
    }
}
